//
// Created by korack on 25-5-14.
//

#include "ApplicationWindow.h"
#include <gtkmm/button.h>
#include <iostream>

namespace Mp {

ApplicationWindow::ApplicationWindow(
  BaseObjectType *cobject, const Glib::RefPtr<Gtk::Builder> &refBuilder)
  : ObjectBase("MpApplicationWindow"), Gtk::ApplicationWindow(cobject),
    m_refBuilder(refBuilder)
{
  m_refCssProvider = Gtk::CssProvider::create();
  Gtk::StyleProvider::add_provider_for_display(
    get_display(), m_refCssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
  m_refCssProvider->signal_parsing_error().connect(
    [](const auto &section, const auto &error) {
      on_parsing_error(section, error);
    });
  m_refCssProvider->load_from_resource("/org/korack/mp/style.css");

  m_connect_button = m_refBuilder->get_widget<Gtk::Button>("connect_button");
  m_connect_button->signal_clicked().connect(
    sigc::mem_fun(*this, &ApplicationWindow::on_connect_button_clicked));

  m_disconnect_button = m_refBuilder->get_widget<Gtk::Button>("disconnect_button");
  m_disconnect_button->signal_clicked().connect(
      sigc::mem_fun(*this, &ApplicationWindow::on_disconnect_button_clicked));
}

void
ApplicationWindow::on_parsing_error(
  const Glib::RefPtr<const Gtk::CssSection> &section, const Glib::Error &error)
{
  std::cerr << "on_parsing_error(): " << error.what() << std::endl;
  if (section)
    {
      if (const auto file = section->get_file())
	{
	  std::cerr << "  URI = " << file->get_uri() << std::endl;
	}

      const auto start_location = section->get_start_location();
      const auto end_location = section->get_end_location();
      std::cerr << "  start_line = " << start_location.get_lines() + 1
		<< ", end_line = " << end_location.get_lines() + 1 << std::endl;
      std::cerr << "  start_position = " << start_location.get_line_chars()
		<< ", end_position = " << end_location.get_line_chars()
		<< std::endl;
    }
}

void
ApplicationWindow::on_connect_button_clicked() const
{
  signal_on_connect_button_clicked.emit();
}

void
ApplicationWindow::on_disconnect_button_clicked() const
{
  signal_on_connect_button_clicked.emit();
}

void
ApplicationWindow::hide_connect_button() const
{
  m_connect_button->set_visible(false);
  m_disconnect_button->set_visible(true);
}


ApplicationWindow *
ApplicationWindow::create()
{
  const auto refBuilder
    = Gtk::Builder::create_from_resource("/org/korack/mp/ui/interface.xml");
  const auto window
    = Gtk::Builder::get_widget_derived<ApplicationWindow>(refBuilder,
							  "app_window");

  if (!window)
    {
      throw std::runtime_error("Failed to create application window");
    }

  return window;
}

} // namespace Mp